#include <rtthread.h>
#include <rtdevice.h>

#include "lwip/sockets.h"

#define SERVER_IP	"180.97.81.180"
//#define SERVER_IP	"127.0.0.1"

#define SERVER_PORT	51935

char recvline[1024];


//udp任务函数
static void tcpclient_thread(void *arg)
{
	int ret;
	
	int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
	//server ip port
	struct sockaddr_in servaddr;
	struct sockaddr_in client_addr;
	char sendline[100] = "hello world!";
	
	memset(&servaddr,0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERVER_PORT);
	servaddr.sin_addr.s_addr = inet_addr(SERVER_IP);
	
	memset(&client_addr, 0, sizeof(client_addr));
	client_addr.sin_family = AF_INET;
	client_addr.sin_port = htons(40001);
	client_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	if(bind(sockfd, (struct sockaddr *)&client_addr,sizeof(client_addr))<0)
	{
		printf("video rtcp bind ret < 0\n");
	}
	sendto(sockfd, sendline, strlen(sendline) + 1, 0, (struct sockaddr *)&servaddr,sizeof(servaddr));
	
	while(1)
	{
		struct sockaddr_in addrClient;
		int sizeClientAddr = sizeof(struct sockaddr_in);
		ret = recvfrom(sockfd, recvline, 1024, 0, (struct sockaddr*)&addrClient,(socklen_t*)&sizeClientAddr);
		char *pClientIP =inet_ntoa(addrClient.sin_addr);
 
		printf("%s-%d(%d) says:%s\n",pClientIP,ntohs(addrClient.sin_port),addrClient.sin_port, recvline);
		
		sendto(sockfd, recvline, ret, 0, (struct sockaddr *)&addrClient, sizeClientAddr);
	}
	
	close(sockfd);
	return ;
}

void udp_demo_init(void)
{
	sys_thread_new("tcpecho_thread", tcpclient_thread, NULL, 5*1024, 3);
}

